import base64, json, requests


class public_ui_utils:

    def screenshot_element(self, page, element_selector, screenshot_path):
        """
        截图指定的元素并保存到文件。

        :param page: Playwright Page 对象
        :param element_selector: 要截图的元素选择器
        :param screenshot_path: 保存截图的文件路径
        """
        locator = page.locator(element_selector)
        locator.screenshot(path=screenshot_path)

    def verification_code(self):
        """
        识别验证码并返回识别结果。
        """
        with open("captcha_image.jpeg", 'rb') as f:
            base64_data = base64.b64encode(f.read())
        b64 = base64_data.decode()

        data = {"username": "ayin", "password": "Qz6528608", "typeid": 1003, "image": b64}
        result = json.loads(requests.post("http://api.ttshitu.com/predict", json=data).text)

        if result['success']:
            return result["data"]["result"]
        else:
            return result["message"]


ui_utils = public_ui_utils()
